package com.czmc.wifivideo

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import androidx.appcompat.app.AppCompatActivity
import com.czmc.wifivideo.net.udp.SearchResult
import com.czmc.wifivideo.net.udp.UDPScanner
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_result.view.*

class MainActivity : AppCompatActivity() {
    private lateinit var scaner: UDPScanner
    private val adapter:ResultsAdapter by lazy {
        ResultsAdapter(this)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Example of a call to a native method
//        sample_text.text = stringFromJNI()

        lv_finded.adapter = adapter
        lv_finded.setOnItemClickListener(adapter)
        scaner = UDPScanner {
            runOnUiThread { adapter.setData(it) }
        }
    }

    open fun beginScan(view: View = button) {
        scaner.start()
    }
    open fun stopScan(view: View = button) {
        scaner.stop()
    }
    open fun beginSearchReceive(view: View = button) {
//        scaner.start()
    }
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    external fun stringFromJNI(): String

    companion object {

        // Used to load the 'native-lib' library on application startup.
        init {
            System.loadLibrary("native-lib")
        }
    }

}

class ResultsAdapter(val context: Context, val data: ArrayList<SearchResult> = ArrayList()) : BaseAdapter(),AdapterView.OnItemClickListener {
    override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        data[p2].ip
    }

    override fun getView(pos: Int, convertView: View?, parent: ViewGroup?): View {
        var view: View
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(R.layout.item_result, null)
        } else {
            view = convertView
        }
        view.tv_ip_port.setText("${getItem(pos).ip}")
        return view
    }

    override fun getItem(p0: Int): SearchResult = data.get(p0)

    override fun getItemId(p0: Int): Long = p0.toLong()

    override fun getCount(): Int = data.count()

    fun setData(data: List<SearchResult>) {
        this.data.clear()
        this.data.addAll(data)
        this.notifyDataSetChanged()
    }

}
